package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    /*
        修改 ShopController 中的业务逻辑,满足下面的需求:
            根据 id 查询店铺时,如果缓存未命中,则查询数据库,将数据库结果写入缓存,并设置超时时间
            根据 id 修改店铺时,先修改数据库,再删除缓存
     */
    @Override
    public Result queryById(Long id) {
        // 缓存穿透
//        Shop shop = this.queryWidthPassThrough(id);

        // 基于互斥锁,解决缓存击穿
//        Shop shop = this.queryWidthMutex(id);

        // 基于逻辑过期,解决缓存击穿
//        Shop shop = this.queryWidthLogicalExpire(id);

        // 解决缓存穿透
//        Shop shop = this.cacheClient.queryWidthPassThrough("cache:shop:", id, Shop.class, this::getById, 30L, TimeUnit.SECONDS);

        // 解决缓存击穿
        Shop shop = this.cacheClient.queryWidthLogicalExpire("cache:shop:", id, Shop.class, this::getById, 30L, TimeUnit.SECONDS);

        if (null == shop) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    // 解决缓存穿透
    public Shop queryWidthPassThrough(Long id) {
        String key = "cache:shop:" + id;
        // 从 redis 中查询商铺缓存
        String shopJson = this.stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            // 存在直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        // 判断命中的是否是空值
        if (shopJson != null) {
            // 返回一个错误信息
            return null;
        }

        // 不存在根据 id 查询数据库
        Shop shop = this.getById(id);
        // 不存在,返回错误
        if (null == shop) {
            // 将空值写入 redis,空值的有效期要低于正常的数据,一般只需要两三分钟即可
            this.stringRedisTemplate.opsForValue().set(key, "", 2L, TimeUnit.MINUTES);
            return null;
        }
        // 存在,写入 redis
        this.stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), 30L, TimeUnit.MINUTES);
        return shop;
    }

    // 基于互斥锁解决缓存击穿
    public Shop queryWidthMutex(Long id) {
        String key = "cache:shop:" + id;
        // 从 redis 中查询商铺缓存
        String shopJson = this.stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            // 存在直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        // 判断命中的是否是空值
        if (shopJson != null) {
            // 返回一个错误信息
            return null;
        }

        // 实现缓存重建,获取互斥锁
        String lockKey = "lock:shop:" + id;
        Shop shop = null;
        try {
            boolean isLock = this.tryLock(lockKey);
            // 判断是否获取成功
            if (!isLock) {
                // 失败则休眠并重试
                Thread.sleep(50);
                return this.queryWidthMutex(id);
            }
            // 成功则根据 ID 查询数据库
            shop = this.getById(id);
            // 不存在,返回错误
            if (null == shop) {
                // 将空值写入 redis,空值的有效期要低于正常的数据,一般只需要两三分钟即可
                this.stringRedisTemplate.opsForValue().set(key, "", 2L, TimeUnit.MINUTES);
                return null;
            }
            // 存在,写入 redis
            this.stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), 30L, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放互斥锁
            this.unlock(lockKey);
        }

        return shop;
    }

    // 线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    // 基于逻辑过期解决缓存击穿
    public Shop queryWidthLogicalExpire(Long id) {
        String key = "cache:shop:" + id;
        // 从 redis 中查询商铺缓存
        String shopJson = this.stringRedisTemplate.opsForValue().get(key);
        // 如果未命中, 代表不是热点 key, 直接返回即可
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }

        // 命中,先把 json 反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        // 过期时间
        LocalDateTime expireTime = redisData.getExpireTime();

        // 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 未过期,直接返回店铺信息
            return shop;
        }

        // 已过期,需要缓存重建
        // 获取互斥锁
        String lockKey = "lock:shop:" + id;
        boolean isLock = this.tryLock(lockKey);
        // 获取锁是否成功
        if (isLock) {
            // 成功,开启独立线程,实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.saveShopRedis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    this.unlock(lockKey);
                }
            });
        }
        // 获取失败直接返回旧的缓存数据
        return shop;
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        String key = "cache:shop:" + id;
        if (null == id) {
            return Result.fail("店铺 id 不能为空");
        }
        // 更新数据库
        this.updateById(shop);
        // 删除缓存
        this.stringRedisTemplate.delete(key);
        return Result.ok();
    }

    // 尝试获取锁
    private boolean tryLock(String key) {
        Boolean flag = this.stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    // 释放锁
    private void unlock(String key) {
        this.stringRedisTemplate.delete(key);
    }

    // 缓存预热
    public void saveShopRedis(Long id, Long expireSeconds) throws InterruptedException {
        // 查询店铺数据
        Shop shop = this.getById(id);

        Thread.sleep(200);
        // 封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 写入 redis
        this.stringRedisTemplate.opsForValue().set("cache:shop:" + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询,按照数据库查询
            Page<Shop> page = this.query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));

            return Result.ok(page.getRecords());
        }

        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 查询 redis、按照距离排序、分页,结果为: shopId、distance
        String key = "shop:geo:" + typeId;

        // GEOSEARCH key FROMLONLAT x y BYRADIUS 10 WITHDISTANCE
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000), // 半径
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
                                .includeDistance()
                                .limit(end)
                );

        // 解析出 id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }

        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了,结束
            return Result.ok(Collections.emptyList());
        }

        // 截取 from 到 end 的部分(查询出来的结果是从 0 到 end)
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());

        list.stream().skip(from).forEach(result -> {
            // 获取店铺 id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));

            // 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });

        // 根据 id 查询 Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = this.query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        return Result.ok(shops);
    }
}
